package com.fzu.mmdbproxyframework.multitask;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;

import com.fzu.mmdbproxyframework.model.MMDataNodeCluster;



/**
 * 定时任务执行器
 * @author 
 *
 */
public class ScheduledTaskExecutor{
	
	private final static Logger logger = LoggerFactory.getLogger(ScheduledTaskExecutor.class);
	
	private ScheduledTask scheduledTask;
	
	private TaskScheduler taskScheduler;
	

	

	/**
	 */
	private ScheduledTaskExecutor() {
	}


	/**
	 * @param cluster
	 */
	public ScheduledTaskExecutor(ScheduledTask scheduledTask) {
		this.scheduledTask = scheduledTask;
	   ScheduledExecutorService localExecutor =  Executors.newSingleThreadScheduledExecutor();;
       taskScheduler =  new ConcurrentTaskScheduler(localExecutor);
       System.out.println("ScheduledTaskExecutor(ScheduledTask scheduledTask) ");
	}

	
	
	public void execute() {
		if(scheduledTask.getCron()!=null){
			logger.info("executing {} by cron", scheduledTask);
			this.taskScheduler.schedule(scheduledTask,new CronTrigger(scheduledTask.getCron()));
		}else if(scheduledTask.getDelay()>=0){
			logger.info("executing {} by delay", scheduledTask);
			this.taskScheduler.scheduleWithFixedDelay(scheduledTask, scheduledTask.getDelay());
		}else{
			logger.warn("invalid {}. because subclass must override getCron() or getDelay().", scheduledTask);
		}
	}

}

